package com.bruce.asurada.sso.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfigurationSource;

import jakarta.annotation.Resource;

/**
 * Spring Security配置类
 * 
 * @author Bruce
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private CorsConfigurationSource corsConfigurationSource;

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 启用CORS支持，并关联我们的CORS配置
            .cors(cors -> cors.configurationSource(corsConfigurationSource))
            // 禁用CSRF保护
            .csrf(csrf -> csrf.disable())
            // 配置会话管理为无状态
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 配置请求授权
            .authorizeHttpRequests(auth -> auth
                // 允许SSO服务端接口无需认证（由业务逻辑控制）
                .requestMatchers("/sso/**").permitAll()
                // 允许验证码服务端接口无需认证（由业务逻辑控制）
                .requestMatchers("/phone/**").permitAll()
                // 允许健康检查接口无需认证
                .requestMatchers("/health/**").permitAll()
                // 其他所有请求都需要认证
                .anyRequest().authenticated()
            )
            // 禁用默认登录页面
            .formLogin(form -> form.disable())
            // 禁用HTTP Basic认证
            .httpBasic(basic -> basic.disable());

        return http.build();
    }
}